package com.ucode.crm.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ucode.crm.dictionary.CrmResultDefineMsg;
import com.ucode.crm.dictionary.ModuleType;
import com.ucode.crm.dictionary.TeamUserPower;
import com.ucode.crm.mapper.BusinessMapper;
import com.ucode.crm.mapper.ContactsMapper;
import com.ucode.crm.mapper.CrmTeamUserMapper;
import com.ucode.crm.mapper.CustomerMapper;
import com.ucode.crm.mode.CrmTeamUser;
import com.ucode.crm.service.CrmTeamUserService;
import com.ucode.tool.base.ResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.util.IdentifyUtils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;

@Service
public class CrmTeamUserServiceImpl implements CrmTeamUserService {

    @Autowired
    private CrmTeamUserMapper crmTeamUserMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private ContactsMapper contactsMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Override
    @Transactional(rollbackFor=Exception.class)
    public int batchInsert(Long targetId, Integer targetType, List<Long> userIds, Integer power) {
        if(CollUtil.isEmpty(userIds))
            return 0;
        
        List<CrmTeamUser> followTeamUsers = new ArrayList<CrmTeamUser>();
        Date now = new Date();
        for(Long userId : userIds){
            CrmTeamUser followupTeamUser = new CrmTeamUser(targetId, targetType, userId, power);
            followupTeamUser.setId(IdentifyUtils.getDefaultSnowflakeId());
            followupTeamUser.setCreatedTime(now);
            followupTeamUser.setUpdatedTime(now);
            followTeamUsers.add(followupTeamUser);
        }
        int i = crmTeamUserMapper.batchSave(followTeamUsers);
        if(i > 0){
            List<Long> oldCrmTeamUsers = crmTeamUserMapper.findCollaborator(targetId, targetType);
            Set<Long> collaborator = new HashSet<>();
            collaborator.addAll(userIds);
            if(CollUtil.isNotEmpty(oldCrmTeamUsers)){
                collaborator.addAll(userIds);
            }
            
            if(collaborator.size() > 25){
                throw new UcodeServiceException(ResultCodeEnum.FAILED.code,CrmResultDefineMsg.teamUser_max_permission_error,25);
            }
            String collaboratorStr = StrUtil.join(",", collaborator);
            if(ModuleType.customer.code == targetType){
                customerMapper.updateCollaborator(targetId, collaboratorStr);
                contactsMapper.updateCollaborator(targetId, collaboratorStr);
            }else if(ModuleType.business.code == targetType){
                businessMapper.updateCollaborator(targetId, collaboratorStr);
            }
            
        }
        return i;
    }

    @Override
    public int updatePower(Long id, Integer power) {
        return crmTeamUserMapper.updatePower(id, power);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int delete(Long id,Long operatorId) {
        CrmTeamUser followupTeamUser = crmTeamUserMapper.findById(id);
        if(followupTeamUser == null)
            return 0;
        
        if(TeamUserPower.owner.code == followupTeamUser.getPower()){
            throw new UcodeServiceException(ResultCodeEnum.ILLEGAL_OPERATION.code,CrmResultDefineMsg.teamUser_owner_delete_error);
        }
        
        return crmTeamUserMapper.delete(followupTeamUser.getId());
    }

    @Override
    public int batchDelete(List<Long> ids,Long operatorId) {
        return crmTeamUserMapper.batchDelete(ids);
    }

    @Override
    public CrmTeamUser findById(Long id) {
        return crmTeamUserMapper.findById(id);
    }
    
    @Override
    public List<CrmTeamUser> findByIds(List<Long> ids) {
        return crmTeamUserMapper.findByIds(ids);
    }

    @Override
    public CrmTeamUser find(Long targetId, Integer targetType, Long userId) {
        return crmTeamUserMapper.find(targetId, targetType, userId);
    }

    @Override
    public List<CrmTeamUser> findList(Long targetId, Integer targetType) {
        return crmTeamUserMapper.findList(targetId, targetType);
    }
}
